package cn.edu.xmu.software.streamplayer.service;

import java.io.IOException;

import cn.edu.xmu.software.streamplayer.R;
import cn.edu.xmu.software.streamplayer.aidl.PlayEngineInterface;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class PlayEngine extends Service {
	public final String TAG = "playEngine";
	private MediaPlayer mp = new MediaPlayer();
	private NotificationManager nm;
	String address = "";
	private static final int NOTIFY_ID = R.layout.player;

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	private final PlayEngineInterface.Stub mBinder = new PlayEngineInterface.Stub() {

		@Override
		public void stop() throws RemoteException {
			nm.cancel(NOTIFY_ID);
			mp.stop();
		}

		@Override
		public void play() throws RemoteException {
			Log.i(TAG, "play file " + address + "!");
			Notification notification = new Notification();
			nm.notify(NOTIFY_ID, notification);
			mp.reset();
			try {
				mp.setDataSource(address);
				mp.start();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		public void pause() throws RemoteException {
			Notification notification = new Notification();
			nm.notify(NOTIFY_ID, notification);
			mp.pause();
		}

		@Override
		public void addSong(String uri) throws RemoteException {
			address = uri;
		}
	};

	public void onCreate() {
		super.onCreate();
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	}

	public void onDestroy() {
		super.onDestroy();
		mp.stop();
		mp.release();
		nm.cancel(NOTIFY_ID);
	}

}
